const query = require("../db/mysql");
const {success, error} = require('../model/model')
class CartController {
    getCartList = async  (ctx) =>{
        const {user_id} = ctx.query;
        const sql = `select * from carts where user_id="${user_id}"`
        const data =await query(sql)
        console.log(sql)
        const allP = data.map(item => {
            return query(`select * from shops where id="${item.shop_id}"`)
        })
        const shops= await Promise.all(allP);
        const newData = data.map((item,index) => {
            return { ...shops[index][0],...item}
        })
        ctx.body = success(newData)
    }
    addToCart = async  (ctx) =>{
        const {user_id, shop_id} = ctx.request.body;
        const isHaveSql = `select * from carts where user_id="${user_id}" and shop_id="${shop_id}"`
        const isHave = await query(isHaveSql)
        let sql = ''
        if(isHave.length) {
            console.log(isHave)
            const nowData = isHave[0]; 
            sql = `update carts set count="${nowData.count+=1}"  where id="${nowData.id}"`
        } else {
            sql = `insert into carts(user_id,shop_id,count) values("${user_id}","${shop_id}",1)`
        }
        const data =await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('添加成功')
        } else {
            ctx.body = error('添加失败')
        }
    }
    delCart = async(ctx) => {
        const {id} = ctx.params;
        const sql = `delete from carts where id ="${id}"`
        const data = await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('删除成功')
        } else {
            ctx.body = error('删除失败')
        }
    }
    setCartCount= async(ctx) => {
        const {id,count} = ctx.request.body;
        const sql = `update carts set count="${count}" where id="${id}"`
        const data = await query(sql)
        if(data.affectedRows === 1){
            ctx.body = success('更新成功')
        } else {
            ctx.body = error('更新失败')
        }
    }
}   

module.exports = new CartController()